package gui;


import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.event.ActionEvent;

import javax.swing.*;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import FTP.FtpClient;
import Projektarbete.Group;
import Projektarbete.Restrictions;
import Projektarbete.User;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author Calle (GUI), Jerry (function, tree)
 */
public class FTPgui extends javax.swing.JPanel {
                    
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JButton deleteButton;
    private JButton downloadButton;
    private JTree fileTree;
    private JScrollPane jScrollPane1;
    private JButton uploadButton;
    private MouseAdapter ml;
    private MouseAdapter ml1;
     
    private FtpClient ftpClient;
	private String filePath = null;

	private PopupMenu popupMenu;
	private MenuItem menuItem;
	private JFrame inputDialog = new JFrame();
	private String defaultPath;

	private String groupName;	
	private String userFolder;
	private String groupID;
	
	private User user;
	private Group group;

      
    public FTPgui(Group group, String gN, int GID, User user) {
    	groupName = gN;
        userFolder = user.getUserName(); 
        this.user = user;
        this.group = group;
        groupID = Integer.toString(GID);
        initComponents();     
    }
                   
    private void initComponents() {

        jScrollPane1 = new JScrollPane();
        fileTree = new JTree();
        uploadButton = new JButton();
        downloadButton = new JButton();
        deleteButton = new JButton();
        
        Restrictions rest = group.getRestrictions(user);
		if (!rest.isDownload()) {
			downloadButton.setEnabled(false);
			downloadButton
					.setToolTipText("You are not allowed to download files");
		}
		if (!rest.isUpload()) {
			uploadButton.setEnabled(false);
			uploadButton.setToolTipText("You are not allowed to upload files");
		}
		if(!rest.isRemove()){
			deleteButton.setEnabled(false);
	    	deleteButton.setToolTipText("You are not allowed to delete files");
		}

        popupMenu = new PopupMenu();
        menuItem = new MenuItem();
        
        
        ftpClient = new FtpClient();
        try {
        	ftpClient.client.changeWorkingDirectory("");
			ftpClient.client.makeDirectory(groupID);
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
        ftpClient.disconnect();
        
        
        groupMap(groupName,groupID);
        
        ftpClient = new FtpClient();
        try {
        	ftpClient.client.changeWorkingDirectory("");
			ftpClient.client.makeDirectory(defaultPath+"/"+userFolder);
			buildTree();
            jScrollPane1.setViewportView(fileTree);
            fileTree.addMouseListener(ml);
            fileTree.addMouseListener(ml1);
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
        ftpClient.disconnect();

        
        menuItem.setLabel("Create a new folder");
        
        menuItem.addActionListener(new java.awt.event.ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		
        		ftpClient = new FtpClient();
        		
        		
        		String name = JOptionPane.showInputDialog(inputDialog,"Enter the name here:", 
        				"Create new folder", JOptionPane.PLAIN_MESSAGE);
        		System.out.println(name);
        		
        		try {
	                                	
            		ftpClient.client.changeWorkingDirectory(defaultPath);
            		System.out.println(defaultPath);

	                if (hasDott(filePath) == false && name != null){
	               
	                	ftpClient.client.makeDirectory(defaultPath+filePath+"/"+name);
	
						buildTree();
	                    jScrollPane1.setViewportView(fileTree);
	                    fileTree.addMouseListener(ml);
	                    fileTree.addMouseListener(ml1);
	                }else if(name != null){
	                }else{
	                	JOptionPane.showMessageDialog(null, "Please choose a folder instead of a file! Try again!");
	                }

                    
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
            	ftpClient.disconnect();
        	}
        });
        popupMenu.add(menuItem);
        add(popupMenu);
  

        ml = new MouseAdapter() {
		     public void mousePressed(MouseEvent e) {
		         int selRow = fileTree.getRowForLocation(e.getX(), e.getY());
		         TreePath selPath = fileTree.getPathForLocation(e.getX(), e.getY());
		         if(selRow != -1) {
		             if(e.getClickCount() == 1) {
		            	 filePath = selPath.toString();
		            	 filePath = filePath.replace("["+groupName, "");
		            	 filePath = filePath.replace("]", "");
		            	 filePath = filePath.replace(", ", "/"); 
		             }
		        }
		    }
		};
		
		ml1 = new MouseAdapter() {
		     public void mousePressed(MouseEvent e) {
		    
		        		int mods=e.getModifiers();
		        	     
		            	if((mods&InputEvent.BUTTON3_MASK)!=0){
		            		popupMenu.show(fileTree,e.getX(),e.getY());
		            	}
		        	
		    }
		};
		
		
		fileTree.addMouseListener(ml);
		fileTree.addMouseListener(ml1);
		


        uploadButton.setText("Upload");
        uploadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uploadFile(evt);
            }

			private void uploadFile(ActionEvent evt) {
				// TODO Auto-generated method stub
				ftpClient = new FtpClient();
	            FileInputStream fis = null;

	            try {   
	                    
	                JFileChooser chooser = new JFileChooser(new File(""));
	                chooser.showOpenDialog(null);
	                
	                File srcFile=new File(chooser.getSelectedFile().getPath());	                
	            	
	        		ftpClient.client.changeWorkingDirectory("");
           
	                    
	                ftpClient.client.makeDirectory(defaultPath+"/"+userFolder);
	                ftpClient.client.changeWorkingDirectory(defaultPath+"/"+userFolder); 
	                
	                    
	                fis = new FileInputStream(srcFile);

	                // ftpClient.setBufferSize(1024);

	                ftpClient.client.setFileType(FTPClient.BINARY_FILE_TYPE);
	                ftpClient.client.storeFile(srcFile.getName(), fis);
	                buildTree();
	                jScrollPane1.setViewportView(fileTree);
	                fileTree.addMouseListener(ml);
	                fileTree.addMouseListener(ml1);

	                    
	            } catch (IOException e1) {
	                e1.printStackTrace();
	                throw new RuntimeException("Client Error", e1);
	            } finally {
	                    IOUtils.closeQuietly(fis);
	               ftpClient.disconnect();
	            }
	        
			}
        });
        
        downloadButton.setText("Download");
        downloadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                downloadFile(evt);
            }

			private void downloadFile(ActionEvent evt) {
				ftpClient = new FtpClient();
	        		
	        		
	                if (filePath != null){
	                	if (hasDott(filePath)){
	                		try {
								ftpClient.client.changeWorkingDirectory("");
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
	                		ftpClient.downloadFile(defaultPath+filePath);
	                		System.out.println("AAA: " + defaultPath+filePath);
	                		ftpClient.disconnect();
	                	}else{     	
	                		try {
	                			ftpClient.client.changeWorkingDirectory(defaultPath+filePath);
	                			FTPFile[] files = ftpClient.client.listFiles();	
	                			ftpClient.client.changeWorkingDirectory("");
							
	                			for (int i = 0; i<files.length; i++){
	                				if (hasDott(files[i].getName()) == true){
	                					ftpClient.downloadFile(defaultPath+filePath+"/"+files[i].getName());
	                					System.out.println("BBB: " + defaultPath+filePath+"/"+files[i].getName());
	                				}else{
	                					JOptionPane.showMessageDialog(downloadButton, "Please choose a userfolder " +
	                							"and try again!");
	                					ftpClient.disconnect();
	                					break;
	                				}
	                			}
							
	                		} catch (IOException e) {
	                			e.printStackTrace();
	                		}
	                		ftpClient.disconnect();
	                	}
	                }
	                else{
	                	JOptionPane.showMessageDialog(downloadButton, "Please choose a file or map and try again!");
	                	ftpClient.disconnect();
	                }
				}
        });

        deleteButton.setText("Delete");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteFile(evt);
            }

			private void deleteFile(ActionEvent evt) {
				ftpClient = new FtpClient();
	            FileOutputStream fos = null;

	            try {
	            	
	        		ftpClient.client.changeWorkingDirectory("");
  
	                
					if (hasDott(filePath) == true){    	                	
	                	ftpClient.client.deleteFile(defaultPath+filePath);
	                	buildTree();
	                    jScrollPane1.setViewportView(fileTree);
	                    fileTree.addMouseListener(ml);
	                    fileTree.addMouseListener(ml1);

	                    
					}else{
	                	JOptionPane.showMessageDialog(deleteButton, "Please choose a file and try again!");
	                }
					
	                    
	            } catch (IOException e1) {
	                e1.printStackTrace();
	                throw new RuntimeException("Client Error", e1);
	            } finally {
	                    IOUtils.closeQuietly(fos);
	                ftpClient.disconnect();
	            }
				
			}
				
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(uploadButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(downloadButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(deleteButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addComponent(uploadButton, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(downloadButton, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(deleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(14, Short.MAX_VALUE))
        );
    }// </editor-fold>    
    


	public boolean hasDott(String path){
    	for (int i = 0; i < path.length(); i++){
        	char c = path.charAt(i);
        	if(c == '.'){
        		return true;
        	}
        }
    	return false;
    }
    
    // build a tree
    public void buildTree(){       
    		
    		DefaultMutableTreeNode totalroot = new DefaultMutableTreeNode(groupName);
    		bind(totalroot,"");
    		DefaultTreeModel TreeModel = new DefaultTreeModel(totalroot, true);
    		fileTree = new JTree(TreeModel);
    		jScrollPane1.setViewportView(fileTree);
    }   
  
        
    // bind nod/subnode to the tree (recursive method)
    public void bind(DefaultMutableTreeNode node,String path){
        try {
        	      	
        		ftpClient.client.changeWorkingDirectory(defaultPath + "/" + path);
        	
        		FTPFile[] files = ftpClient.client.listFiles();
			
        		for(int i=0;i<files.length;i++){
        			FTPFile tempFile = files[i];
        			if(tempFile.isDirectory()){
        				DefaultMutableTreeNode tempNode = new DefaultMutableTreeNode(tempFile.getName(),true);
        				node.add(tempNode);
        				bind(tempNode, path+"/"+tempFile.getName());
	            }else{
	                	DefaultMutableTreeNode tempNode = new DefaultMutableTreeNode(tempFile.getName(),false);
	                	node.add(tempNode);
	            }
	        }
        
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
    }
    
  
    public void groupMap(String gN, String gID){

        try {
        	
        	ftpClient = new FtpClient();
			ftpClient.client.changeWorkingDirectory("/"+gID);
			ftpClient.client.makeDirectory(gN);
			
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        
        	defaultPath = "/"+gID + "/" + gN;
        	System.out.println("ready:" + defaultPath);
        	buildTree();
        	ftpClient.disconnect();
        	jScrollPane1.setViewportView(fileTree);
        	fileTree.addMouseListener(ml);
        	fileTree.addMouseListener(ml1);
        
    		
    }            
}
